package com.entities;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Match {

	public static final String TAG_PLAYERS = "players";
	public static final String TAG_LOBBY_TYPE = "lobby_type";
	public static final String TAG_START_TIME = "start_time";
	public static final String TAG_MATCH_SEQ_NUM = "match_seq_num";
	public static final String TAG_MATCH_ID = "match_id";
	public static final String TAG_MATCHES = "matches";
	
	protected Long match_id;
	protected Long match_seq_num;
	protected Long start_time;
	protected int lobby_type;

	public static HashMap <String, List<Match>> mapList = new  HashMap<String, List<Match>>();
	
	
	
	protected List<Player> players;

	
	public Long getMatch_id() {
		return match_id;
	}
	public Long getMatch_seq_num() {
		return match_seq_num;
	}
	public Long getStart_time_in_miliseconds() {
		return start_time*1000;
	}
	public int getLobby_type() {
		return lobby_type;
	}

	public Long getStart_time() {
		
		return start_time;
	}
	
	public List<Player> getPlayers() {
		return players;
	}
	
	public int getHeroIdOfAccId(String accId){
		for(Player p: players){
			if(p.getAccount_id().equals(Long.valueOf(accId))){
				return p.getHero_id();
			}
		}
		return -1;
	}


	Match(){
		
	}
	

	
	public Match (JSONObject json) throws JSONException{
		
		List<Player> players = new ArrayList<Player>();
		JSONArray playersJSONArray = json.getJSONArray(TAG_PLAYERS);
		for(int pc = 0; pc<playersJSONArray.length(); pc++){
			JSONObject pl = playersJSONArray.getJSONObject(pc);
			players.add(new Player(pl.getLong(Player.TAG_ACC_IC), pl.getInt(Player.TAG_PLAYER_SLOT), pl.getInt(Player.TAG_HERO_ID))) ;
		}
		long match_id = json.getLong(TAG_MATCH_ID);
		long match_seq_num = json.getLong(TAG_MATCH_SEQ_NUM);
		long start_time = json.getLong(TAG_START_TIME);
		int lobby_type = json.getInt(TAG_LOBBY_TYPE);
		
		
		
		this.match_id= match_id;
		this.match_seq_num = match_seq_num;
		this.start_time = start_time;
		this.lobby_type = lobby_type;
		this.players = players;
		
	}
	
	

	public static List<Match> getMatchsFromJSONArray(JSONArray matchs){
		
		List<Match> mList = new ArrayList<Match>();
		try {
		for(int cont = 0; cont<matchs.length(); cont++){

			JSONObject json = matchs.getJSONObject(cont);
			mList.add(new Match(json));	
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return mList;
	}
	
}
